/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teach.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.ConstantEnum;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ReturnObject;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.web.ExcelController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachAchievement;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachAward;
import com.thinkgem.jeesite.modules.teach.service.TpTeachAwardService;

/**
 * 讲课比赛Controller
 * @author 康力
 * @version 2018-03-11
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/tpTeachAward")
public class TpTeachAwardController  extends ExcelController<TpTeachAward> {
	@Autowired
	private SystemService systemService;
	@Autowired
	private TpTeachAwardService tpTeachAwardService;


	private String defaultStr="/teach/tpTeachAward/?repage";

	@ModelAttribute
	public TpTeachAward get(@RequestParam(required=false) String id) {
		TpTeachAward entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpTeachAwardService.get(id);
		}
		if (entity == null){
			entity = new TpTeachAward();
		}
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		entity.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachAward:view"));
		if (entity.getIsNewRecord() && entity.getUserDataScope() == 0) {// 个人数据权限，获取个人信息
			entity.setUser(UserUtils.getUser());// 设置人员
			if (entity.getUser() != null) {
				entity.setDepartment(entity.getUser().getOffice());// 设置科室
				if (entity.getDepartment() != null) {
					// 设置教研室
					entity.setTrc(systemService.findParentByOfficeId(entity.getDepartment().getId()));
				}
			}
		}
		return entity;
	}
	
	@RequiresPermissions("teach:tpTeachAward:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpTeachAward tpTeachAward, HttpServletRequest request, HttpServletResponse response, Model model) {
		String str = request.getRequestURI().replaceFirst(request.getContextPath()+Global.getConfig("adminPath"), "");
		model.addAttribute("remark",systemService.getRemark(str));
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		tpTeachAward.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachAward:view"));
		if(tpTeachAward.getUserDataScope() == 0){
			tpTeachAward.setUser(UserUtils.getUser());
		}else{//获得当前登录人部门下的数据
			if(tpTeachAward.getDepartment() == null && !tpTeachAward.getIsStudent())tpTeachAward.setDepartment(UserUtils.getUser().getOffice());
		}
		Page<TpTeachAward> page = tpTeachAwardService.findPage(new Page<TpTeachAward>(request, response), tpTeachAward);
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			rtobj.setData(page);
			return renderString(response, rtobj);
		}
		model.addAttribute("page", page);
		model.addAttribute("isStudent", request.getParameter("isStudent"));
		return "modules/teach/tpTeachAwardList";
	}

	@RequiresPermissions("teach:tpTeachAward:view")
	@RequestMapping(value = "form")
	public String form(TpTeachAward tpTeachAward, Model model, HttpServletRequest request, HttpServletResponse response) {
		//如果为新增数据并且数据权限为个人数据的情况下，启动审批流程
		String viewName = "";
		if(tpTeachAward == null ||
				(tpTeachAward.getStatus()!= null && tpTeachAward.getStatus() == 2)||
				(StringUtils.isBlank(tpTeachAward.getId())&&StringUtils.isBlank(tpTeachAward.getAct().getProcInsId()))){
			//根据流程名称获取最新的流程实例名称
			String procDefId = null;
			if(systemService.getCurUserDataScopeByPermission("teach:tpTeachAward:view") == 0){
				if(tpTeachAward.getIsStudent()){//学员数据，走学员专用审批流程
					procDefId = systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_AWARD_STUDENT[0]);
				}else{
					procDefId = systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_AWARD[0]);
				}
			}
			Act act = new Act();
			act.setProcDefId(procDefId);
			tpTeachAward.setAct(act);
			viewName="tpTeachAwardForm";
		} else if (tpTeachAward.getAct() != null && tpTeachAward.getAct().getTaskDefKey() != null
				&& tpTeachAward.getAct().getTaskDefKey().startsWith("audit")
				&&tpTeachAward.getAct().isTodoTask()) {
			viewName="tpTeachAwardAudit";
		}else{
			viewName="tpTeachAwardView";
			//如果实体类内容未查出，使用ProcInsId查询
			Act act = tpTeachAward.getAct();
			if(StringUtils.isBlank(tpTeachAward.getId()) && act != null
					&& StringUtils.isNotBlank(act.getProcInsId())){
				tpTeachAward.setProcInsId(act.getProcInsId());
				List<TpTeachAward> list = tpTeachAwardService.findList(tpTeachAward);
				if(list.size() == 1){
					tpTeachAward = list.get(0);
					tpTeachAward.setAct(act);
				}
			}
		}
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			ExportExcel ex = new ExportExcel("教学成果", TpTeachAward.class);
			tpTeachAward = ex.getMobileDataList(tpTeachAward);
			tpTeachAward.setPropertyNameMap(ex.getPropertyNameMap());
			rtobj.setData(tpTeachAward);
			return renderString(response, rtobj);
		}
		model.addAttribute("isStudent", request.getParameter("isStudent"));
		model.addAttribute("tpTeachAward", tpTeachAward);
		return "modules/teach/"+viewName;
	}

	@RequiresPermissions("teach:tpTeachAward:edit")
	@RequestMapping(value = "save")
	public String save(TpTeachAward tpTeachAward, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
		if (!beanValidator(model, tpTeachAward)){
			return form(tpTeachAward, model,request,response);
		}
		tpTeachAwardService.save(tpTeachAward);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachAward/list?isStudent="+request.getParameter("isStudent");
	}
	
	@RequiresPermissions("teach:tpTeachAward:edit")
	@RequestMapping(value = "delete")
	public String delete(TpTeachAward tpTeachAward, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tpTeachAwardService.delete(tpTeachAward);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachAward/list?isStudent="+request.getParameter("isStudent");
	}

	@Override
	protected TpTeachAwardService getService() {
		return tpTeachAwardService;
	}

	/**
	 * 下载导入数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("teach:tpTeachAward:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		try {
			String fileName = "数据导入模板.xlsx";
			List<TpTeachAward> list = Lists.newArrayList();
			new ExportExcel("导入模板", TpTeachAward.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachAward/list?isStudent="+request.getParameter("isStudent");
	}

	/**
	 * 导入
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("teach:tpTeachAward:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TpTeachAward> list = ei.getDataList(TpTeachAward.class);
			systemService.setFieldId(list);
			for (TpTeachAward t : list){
				try{
						tpTeachAwardService.save(t);
						successNum++;
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>名称： "+t.getTitle()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>名称： "+t.getTitle()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条记录，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条记录"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入记录失败！失败信息："+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/teach/tpTeachAward/list?isStudent=" + request.getParameter("isStudent");
	}
	/**
	 * 导出用户数据
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("teach:tpTeachAward:view")
	@RequestMapping(value = "export", method= RequestMethod.POST)
	public String exportFile(TpTeachAward t, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = (t.getIsStudent() ? "获奖情况" : "讲课比赛")+ DateUtils.getDate("yyyy-MM-dd")+".xlsx";
			List<TpTeachAward> data = tpTeachAwardService.findList(t);
			if(t.getIsStudent()){
				new ExportExcel("获奖情况", TpTeachAward.class,3).setDataList(data).write(response, fileName).dispose();
			}else{
				new ExportExcel(getTitle(), TpTeachAward.class).setDataList(data).write(response, fileName).dispose();
			}
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出记录失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + defaultStr;
	}

	@Override
	public String getTitle() {
		// TODO Auto-generated method stub
		return "讲课比赛";
	}

	@Override
	public String defaultStr() {
		// TODO Auto-generated method stub
		return defaultStr;
	}

	@Override
	public CrudService baseService() {
		// TODO Auto-generated method stub
		return tpTeachAwardService;
	}
	
}